package GroupChat;/*

 */

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @ClassName GroupChatClient
 * @Author Final
 * @Project DataStructures
 */
public class GroupChatClient {

    private final String host;

    private final int port;

    public GroupChatClient(String host,int port){
        this.host=host;
        this.port=port;
    }

    public void run() throws InterruptedException {
        EventLoopGroup eventExecutors=new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap().group(eventExecutors).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {

                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("decoder",new StringDecoder());
                    pipeline.addLast("encoder",new StringEncoder());
                    pipeline.addLast(new GroupChatHandler());
                }
            });

        ChannelFuture channelFuture = bootstrap.connect(host, port).sync();

            System.out.println("---------"+channelFuture.channel().localAddress());

            Scanner scanner = new Scanner(System.in);
            //客户端需要输入信息，创建一个扫描器
            while (scanner.hasNextLine()){
                String s = scanner.nextLine();
                channelFuture.channel().writeAndFlush(s);
            }
        }finally {
            eventExecutors.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
       new GroupChatClient("127.0.0.1",9000).run();
    }
}
